package com.libnetwork.models

import com.libbase.MapCodable
import com.libbase.cast

data class ServiceAddressModel(
    var apiBaseUrls: MutableList<String>, var apiBaseUrlIndex: Int,
    var h5BaseUrls: MutableList<String>, var h5BaseUrlIndex: Int,
    var webSocketUrls: MutableList<String>, var webSocketUrlIndex: Int,
) : MapCodable {
    companion object {
        fun create(map: Map<String, Any>): ServiceAddressModel? {
            val apiBaseUrls: List<String> = cast(map["apiBaseUrls"]) ?: return null
            val apiBaseUrlIndex: Int = map["apiBaseUrlIndex"] as? Int ?: return null

            val h5BaseUrls: List<String> = cast(map["h5BaseUrls"]) ?: return null
            val h5BaseUrlIndex: Int = map["h5BaseUrlIndex"] as? Int ?: return null

            val webSocketUrls: List<String> =
                cast(map["webSocketUrls"]) ?: return null
            val webSocketUrlIndex: Int = map["webSocketUrlIndex"] as? Int ?: return null

            return ServiceAddressModel(
                apiBaseUrls.toMutableList(), apiBaseUrlIndex,
                h5BaseUrls.toMutableList(), h5BaseUrlIndex,
                webSocketUrls.toMutableList(), webSocketUrlIndex
            )
        }
    }

    val apiBaseUrl: String?
        get() {
            if (apiBaseUrlIndex < 0 || apiBaseUrlIndex >= apiBaseUrls.count()) {
                return null
            }

            return apiBaseUrls[apiBaseUrlIndex]
        }

    val h5BaseUrl: String?
        get() {
            if (h5BaseUrlIndex < 0 || h5BaseUrlIndex >= h5BaseUrls.count()) {
                return null
            }

            return h5BaseUrls[h5BaseUrlIndex]
        }

    val webSocketUrl: String?
        get() {
            if (webSocketUrlIndex < 0 || webSocketUrlIndex >= webSocketUrls.count()) {
                return null
            }

            return webSocketUrls[h5BaseUrlIndex]
        }

    override fun toMap(): Map<String, Any> {
        return mapOf(
            "apiBaseUrls" to apiBaseUrls,
            "apiBaseUrlIndex" to apiBaseUrlIndex,
            "h5BaseUrls" to h5BaseUrls,
            "h5BaseUrlIndex" to h5BaseUrlIndex,
            "webSocketUrls" to webSocketUrls,
            "webSocketUrlIndex" to webSocketUrlIndex,
        )
    }
}